import TencentCloudChat, { Conversation } from '@tencentcloud/chat'
import { useTencentMessageStore } from '@/stores/tencentMessageStore.ts'
import { useTencentUserStore } from '@/stores/tencentUserStore.ts'
import { useTencentGroupStore } from '@/stores/tencentGroupStore.ts'
import { useGlobalStore } from '@/stores/global.ts'
import { useTencentChat } from '@/stores/tencentChat.ts'

export const useTencentConversationStore = defineStore(
  'TencentConversation',
  () => {
    const tencentUserStore = useTencentUserStore()
    const tencentChat = useTencentChat()
    const tencentMessageStore = useTencentMessageStore()
    const { deleteFriend } = useTencentUserStore()
    const tencentGroup = useTencentGroupStore()
    const globalStore = useGlobalStore()

    const convList = ref<Conversation[]>([])
    const conversationProfile = ref<Partial<Conversation>>({})
    const currentConv = ref<Partial<Conversation>>({})
    const totalUnreadMessageCount = ref(0)
    const currentConversationUserStatus = ref([])
    const currentConversation = computed(() => currentConv)

    const conversationList = computed(() => {
      return convList.value.filter((conv) => {
        if (conv.type !== TencentCloudChat.TYPES.CONV_SYSTEM) {
          if (conv.lastMessage?.type === TencentCloudChat.TYPES.MSG_CUSTOM) {
            return conv.lastMessage?.fromAccount === tencentUserStore.myProfile.userID
          }

          return true
        }

        return false
      })
    })

    const menuList = ref<OPT.RightMenu[]>([
      {
        label: '复制账号',
        icon: 'copy',
        click: async (item: Conversation) => {
          const account =
            item.type === TencentCloudChat.TYPES.CONV_GROUP ? item.groupProfile.name : item.userProfile.userID
          await navigator.clipboard.writeText(account)
          window.$message.success(`复制成功 ${account}`)
        }
      },
      {
        label: (item: Conversation) => {
          console.log(item)
          return item.isPinned ? '取消置顶' : '置顶'
        },
        icon: (item: Conversation) => (item.isPinned ? 'to-bottom' : 'to-top'),
        click: async (item: Conversation) => {
          await pinConversation({ conversationID: item.conversationID, isPinned: !item.isPinned })
        }
      },
      {
        label: '标记未读',
        icon: 'message-unread'
      },
      {
        label: (item: Conversation) => {
          if (item.type === TencentCloudChat.TYPES.CONV_GROUP) {
            return '群消息设置'
          }

          return item.messageRemindType === TencentCloudChat.TYPES.MSG_REMIND_ACPT_AND_NOTE
            ? '设置免打扰'
            : '取消免打扰'
        },
        icon: (item: Conversation) => {
          if (item.type === TencentCloudChat.TYPES.CONV_GROUP) {
            return 'peoples-two'
          }
          return item.messageRemindType === TencentCloudChat.TYPES.MSG_REMIND_ACPT_AND_NOTE ? 'close-remind' : 'remind'
        },
        children: (item: Conversation) => {
          if (item.type === TencentCloudChat.TYPES.CONV_C2C) return null

          return [
            {
              label: '允许消息提醒',
              icon: item.messageRemindType === TencentCloudChat.TYPES.MSG_REMIND_ACPT_AND_NOTE ? 'check-small' : '',
              click: async () => {
                await tencentMessageStore.setMessageRemindType({
                  groupID: item.groupProfile.groupID,
                  messageRemindType: TencentCloudChat.TYPES.MSG_REMIND_ACPT_AND_NOTE
                })
              }
            },
            {
              label: '接收消息但不提醒',
              icon: item.messageRemindType === TencentCloudChat.TYPES.MSG_REMIND_ACPT_NOT_NOTE ? 'check-small' : '',
              click: async () => {
                await tencentMessageStore.setMessageRemindType({
                  groupID: item.groupProfile.groupID,
                  messageRemindType: TencentCloudChat.TYPES.MSG_REMIND_ACPT_NOT_NOTE
                })
              }
            },
            {
              label: '屏蔽群消息',
              icon: item.messageRemindType === TencentCloudChat.TYPES.MSG_REMIND_DISCARD ? 'check-small' : '',
              click: async () => {
                await tencentMessageStore.setMessageRemindType({
                  groupID: item.groupProfile.groupID,
                  messageRemindType: TencentCloudChat.TYPES.MSG_REMIND_DISCARD
                })
              }
            }
          ]
        },
        click: async (item: Conversation) => {
          if (item.type === TencentCloudChat.TYPES.CONV_GROUP) return // 群聊不执行点击事件

          const options = {
            userIDList: [item.userProfile.userID],
            messageRemindType: TencentCloudChat.TYPES.MSG_REMIND_ACPT_AND_NOTE
          }

          if (item.messageRemindType === TencentCloudChat.TYPES.MSG_REMIND_ACPT_AND_NOTE) {
            options.messageRemindType = TencentCloudChat.TYPES.MSG_REMIND_ACPT_NOT_NOTE
          }

          await tencentMessageStore.setMessageRemindType(options)
        }
      }
    ])

    const specialMenuList = ref<OPT.RightMenu[]>([
      {
        label: '从消息列表中移除',
        icon: 'delete',
        click: async (item: Conversation) => {
          await deleteConversation({ conversationIDList: [item.conversationID], clearHistoryMessage: false })
        }
      },
      {
        label: (item: Conversation) => {
          if (item.type === TencentCloudChat.TYPES.CONV_C2C) return '删除好友'
          if (item.type === TencentCloudChat.TYPES.CONV_GROUP) {
            return item.groupProfile.ownerID === item.groupProfile.selfInfo.userID ? '解散群聊' : '退出群聊'
          }

          return ''
        },
        icon: (item: Conversation) => {
          if (item.type === TencentCloudChat.TYPES.CONV_C2C) return 'forbid'
          if (
            item.type === TencentCloudChat.TYPES.CONV_GROUP &&
            item.groupProfile.ownerID === item.groupProfile.selfInfo.userID
          )
            return 'delete'
          return 'logout'
        },
        click: async (item: Conversation) => {
          // 单聊：删除好友
          if (item.type === TencentCloudChat.TYPES.CONV_C2C) {
            deleteFriend({ userIDList: [item.userProfile.userID] })
            return
          }

          // 群聊：解散或退出
          if (item.type === TencentCloudChat.TYPES.CONV_GROUP) {
            if (item.groupProfile.ownerID === item.groupProfile.selfInfo.userID) {
              tencentGroup.dismissGroup(item.groupProfile.groupID)
            } else {
              tencentGroup.quitGroup(item.groupProfile.groupID)
            }
          }
        },
        visible: (item: Conversation) => {
          // 单聊：只在operate为DELETE_FRIEND时显示
          if (item.type === TencentCloudChat.TYPES.CONV_C2C) {
            return false
          }

          // 群聊：始终显示退出选项，如果是群主则显示解散选项
          return true
        }
      }
    ])

    /**
     * 会话列表
     */
    const getConversationList = () => {
      currentConv.value = {}
      tencentChat.chat?.getConversationList()
        .then((res) => {
          convList.value.push(...res.data.conversationList)
          // sortAndUniqueConversationList()
        })
        .catch((error) => {
          window.alert(`会话列表错误：${error}`)
        })
    }

    /** 会话列表去重并排序 */
    const sortAndUniqueConversationList = () => {
      const temp: Record<string, Conversation> = {}
      for (const item of convList.value) {
        temp[item.conversationID] = item
      }
      convList.value.splice(0, convList.value.length, ...Object.values(temp))
      // convList.value.sort((pre, cur) => cur.lastMessage?.lastTime - pre.lastMessage?.lastTime)
    }

    /**
     * 会话详情
     * @param conversationID
     */
    const getConversationProfile = async (conversationID: string) => {
      await tencentChat.chat?.getConversationProfile(conversationID)
        .then((res) => {
          conversationProfile.value = { ...res.data.conversation }
          setCurConv(res.data.conversation)

          if (conversationProfile.value.type === TencentCloudChat.TYPES.CONV_GROUP) {
            tencentGroup.setCurrentGroup(conversationProfile.value?.groupProfile?.groupID!)
          }
        })
        .catch((error) => {
          console.error('获取会话资料错误', error)
        })
    }

    /**
     * 删除会话
     * @param options
     */
    const deleteConversation = async (options: any) => {
      await tencentChat.chat?.deleteConversation(options)
        .then((res) => {
          const { conversationID } = res.data
          if (conversationID === currentConv.value?.conversationID) {
            currentConv.value = {}
          }
        })
        .catch((error) => {
          window.$message.error(`会话删除错误：${error}`)
        })
    }

    /**
     * 会话置顶
     * @param options
     */
    const pinConversation = async (options: { conversationID: string; isPinned: boolean }) => {
      await tencentChat.chat?.pinConversation(options)
        .then((res) => {
          window.$message.success(options.isPinned ? '已置顶' : '已取消置顶')
          console.log(res)
          // 被置顶的会话ID
          // const { conversationID } = res.data
          // getConversationProfile(conversationID)
        })
        .catch(function (error) {
          // const { code } = error
          // code - 50002 会话 ID 无效
          window.$message.error(`置顶失败: ${error}`) // 置顶会话失败的相关信息
        })
    }

    const setCurConv = (conv: Conversation) => {
      currentConv.value = conv
      globalStore.currentConversation = conv
      // window.$message.success(`选择了会话：${currentConv.value.conversationID}`)
    }

    const isC2C = computed(() => currentConv.value?.type === TencentCloudChat.TYPES.CONV_C2C)

    const isGROUP = computed(() => currentConv.value?.type === TencentCloudChat.TYPES.CONV_GROUP)

    const isSYSTEM = computed(() => currentConv.value?.type === TencentCloudChat.TYPES.CONV_SYSTEM)

    /**
     * 获取未读总数
     */
    const getTotalUnreadMessageCount = () => {
      totalUnreadMessageCount.value = tencentChat.chat?.getTotalUnreadMessageCount() as number
      // console.log(`未读消息总数：${totalUnreadMessageCount.value}`)
    }

    const setMessageRead = (conversationID: string) => {
      // 将某会话下所有未读消息已读上报
      tencentChat.chat?.setMessageRead({ conversationID: conversationID })
        .then(function (imResponse) {
          // 已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
          console.log('set message read', imResponse)
        })
        .catch(function (imError) {
          // 已读上报失败
          console.warn('setMessageRead error:', imError)
        })
    }

    const setAllMessageRead = (scope: TencentCloudChat.TYPES = TencentCloudChat.TYPES.READ_ALL_MSG) => {
      // 将所有会话的未读消息全部设置为已读
      // 等同于 tencentChat.chat?.setAllMessageRead({scope: TIM.TYPES.READ_ALL_MSG})
      tencentChat.chat?.setAllMessageRead({ scope: scope })
        .then(function (imResponse) {
          // 已读上报成功，所有会话的 unreadCount 属性值被置为0
          console.log('set all message read', imResponse)
        })
        .catch(function (imError) {
          // 已读上报失败
          console.warn('setAllMessageRead error:', imError)
        })
    }

    /**
     * 设置会话草稿
     * @param options
     */
    const setConversationDraft = (options: { conversationID: string; draftText: string }) => {
      tencentChat.chat?.setConversationDraft(options).then((res) => {
        // TODO
        console.log('set conversation draft', res)
      })
    }

    const markConversation = (options: any) => {
      options = {
        conversationIDList: ['GROUPtest', 'C2Cexample'],
        markType: TencentCloudChat.TYPES.CONV_MARK_TYPE_STAR,
        enableMark: true
      }
      // 会话标星
      tencentChat.chat?.markConversation(options)
        .then(function (imResponse) {
          console.log('mark conversation', imResponse)
          // 会话标星成功
          // const { successConversationIDList, failureConversationIDList } = imResponse.data
          // console.log('success conversation id list', successConversationIDList)
          // successConversationIDList - 标星成功的会话 ID 列表
          // 获取会话列表
          // const conversationList = TencentCloudChat.getConversationList(successConversationIDList);

          // failureConversationIDList - 标星失败的会话 ID 列表
          // failureConversationIDList.forEach((item) => {
          //   const { conversationID, code, message } = item
          //   console.log('failure conversation id list', conversationID, code, message)
          // })
        })
        .catch(function (imError) {
          console.warn('markConversation error:', imError)
        })
    }

    const createConversationGroup = (options: any) => {
      options = {
        conversationIDList: ['GROUPtest', 'C2Cexample'],
        groupName: 'Suppliers'
      }
      tencentChat.chat?.createConversationGroup(options)
        .then(function (imResponse) {
          console.log('create conversation group', imResponse)
          // 创建会话分组成功
          // const { successConversationIDList, failureConversationIDList } = imResponse.data
          // successConversationIDList - 成功的会话 ID 列表
          // 获取会话列表
          // const conversationList = tencentChat.chat?.getConversationList(successConversationIDList)

          // failureConversationIDList - 失败的会话 ID 列表
          // failureConversationIDList.forEach((item) => {
          //   const { conversationID, code, message } = item
          // })
        })
        .catch(function (imError) {
          console.warn('createConversationGroup error:', imError)
        })
    }

    const deleteConversationGroup = (groupName: string) => {
      tencentChat.chat?.deleteConversationGroup(groupName)
        .then(function () {
          // 删除成功
        })
        .catch(function (imError) {
          console.warn('deleteConversationGroup error:', imError)
        })
    }

    const renameConversationGroup = (options: any) => {
      options = {
        oldName: 'Suppliers_old',
        newName: 'Suppliers_new'
      }
      tencentChat.chat?.renameConversationGroup(options)
        .then(function (imResponse) {
          // 重命名成功
          console.log('rename conversation group', imResponse)
        })
        .catch(function (imError) {
          console.warn('renameConversationGroup error:', imError)
        })
    }

    const getConversationGroupList = (options: any) => {
      options = { groupName: 'Suppliers' }
      // 获取指定会话分组下的所有会话
      tencentChat.chat?.getConversationList(options).then(function (imResponse) {
        convList.value = imResponse.data.conversationList // 会话列表
      })
    }

    const addConversationsToGroup = (options?: any) => {
      options = {
        conversationIDList: ['GROUPtest', 'C2Cexample'],
        groupName: 'Suppliers_new'
      }
      tencentChat.chat?.addConversationsToGroup(options)
        .then(function (imResponse) {
          console.log('add conversations to group', imResponse)
          // 添加会话到分组成功
          // const { successConversationIDList, failureConversationIDList } = imResponse.data
          // successConversationIDList - 成功的会话 ID 列表
          // 获取会话列表
          // const conversationList = tencentChat.chat?.getConversationList(successConversationIDList);

          // failureConversationIDList - 失败的会话 ID 列表
          // failureConversationIDList.forEach((item) => {
          //   const { conversationID, code, message } = item
          // })
        })
        .catch(function (imError) {
          console.warn('addConversationsToGroup error:', imError)
        })
    }

    const deleteConversationsFromGroup = (options?: any) => {
      options = {
        conversationIDList: ['GROUPtest', 'C2Cexample'],
        groupName: 'Suppliers_new'
      }
      tencentChat.chat?.deleteConversationsFromGroup(options)
        .then(function (imResponse) {
          console.log(imResponse)
          // 从分组删除会话成功
          // const { successConversationIDList, failureConversationIDList } = imResponse.data
          // successConversationIDList - 成功的会话 ID 列表
          // 获取会话列表
          // const conversationList = tencentChat.chat?.getConversationList(successConversationIDList);

          // failureConversationIDList - 失败的会话 ID 列表
          // failureConversationIDList.forEach((item) => {
          //   const { conversationID, code, message } = item
          // })
        })
        .catch(function (imError) {
          console.warn('deleteConversationsFromGroup error:', imError)
        })
    }

    const resetCurrentConv = () => currentConv.value = {}

    const deleteConversationByGroupID = async (groupID: string) => {
      const conv = convList.value.find((conv: Conversation) => {
        return conv.type === TencentCloudChat.TYPES.CONV_GROUP && conv.groupProfile.groupID === groupID
      })

      if (conv) {
        await deleteConversation(conv.conversationID)
      }
    }

    return {
      convList,
      conversationList,
      getConversationList,
      conversationProfile,
      getConversationProfile,
      currentConversation,
      currentConv,
      setCurConv,
      isC2C,
      isGROUP,
      isSYSTEM,
      deleteConversation,
      pinConversation,
      totalUnreadMessageCount,
      setConversationDraft,
      getTotalUnreadMessageCount,
      currentConversationUserStatus,
      sortAndUniqueConversationList,
      addConversationsToGroup,
      deleteConversationsFromGroup,
      setMessageRead,
      setAllMessageRead,
      createConversationGroup,
      deleteConversationGroup,
      getConversationGroupList,
      markConversation,
      renameConversationGroup,
      menuList,
      specialMenuList,
      resetCurrentConv,
      deleteConversationByGroupID
    }
  },
  {
    share: {
      enable: true,
      initialize: true
    }
  }
)
